<template>
  <div class="ai-hub-container">
    <!-- 顶部导航栏 -->
    <div class="header">
      <div class="header-left">
        <h1>灵动制联 AI Hub</h1>
      </div>
      <div class="header-right">
        <el-button icon="el-icon-moon" circle size="small"></el-button>
      </div>
    </div>

    <!-- 主体内容区域 -->
    <div class="main-content">
      <!-- 左侧会话记录 -->
      <div class="sidebar">
        <div class="sidebar-header">
          <span>咨询记录</span>
          <el-button type="primary" size="mini" @click="newChat">新对话</el-button>
        </div>
        <div class="chat-sessions">
          <div
            v-for="session in chatSessions"
            :key="session.id"
            :class="['session-item', { active: currentSessionId === session.id }]"
            @click="switchSession(session.id)">
            <i class="el-icon-chat-dot-round"></i>
            <span class="session-title">{{ session.title }}</span>
            <span class="session-id">咨询 {{ session.id }}</span>
          </div>
        </div>
      </div>

      <!-- 右侧聊天区域 -->
      <div class="chat-area">
        <!-- 聊天头部 -->
        <div class="chat-header">
          <div class="chat-title">
            <div class="ai-avatar">
              <i class="el-icon-cpu"></i>
            </div>
            <div class="title-content">
              <span class="ai-name">小钢</span>
              <div class="ai-status">
                <span class="status-dot"></span>
                <span>在线服务中</span>
              </div>
            </div>
          </div>
          <div class="chat-subtitle">灵动制联MES系统智能助理</div>
        </div>

        <!-- 聊天消息区域 -->
        <div class="chat-messages" ref="chatMessages">
          <div v-for="(message, index) in currentMessages" :key="index"
               :class="['message-wrapper', message.sender]">
            <div class="message-avatar">
              <i v-if="message.sender === 'user'" class="el-icon-user"></i>
              <i v-else-if="message.sender === 'thinking'" class="el-icon-loading thinking-icon"></i>
              <i v-else class="el-icon-monitor"></i>
            </div>
            <div class="message-content">
              <div class="message-text"
                   :class="{ 'thinking-text': message.sender === 'thinking' }"
                   v-html="formatMessage(message.text)"></div>
              <div class="message-time" v-if="message.sender !== 'thinking'">{{ message.timestamp }}</div>
            </div>
          </div>
        </div>

        <!-- 快捷问题区域 -->
        <div class="quick-questions" v-if="showQuickQuestions">
          <div class="quick-questions-header">
            <span>常用问题</span>
            <el-button type="text" size="mini" @click="showQuickQuestions = false">
              <i class="el-icon-close"></i>
            </el-button>
          </div>
          <div class="quick-questions-content">
            <div class="role-questions" v-for="role in quickQuestionRoles" :key="role.name">
              <div class="role-title">{{ role.name }}</div>
              <div class="questions-grid">
                <el-button
                  v-for="question in role.questions"
                  :key="question"
                  class="question-btn"
                  size="mini"
                  @click="sendQuickQuestion(question)">
                  {{ question }}
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="chat-input">
          <div class="input-wrapper">
            <el-input
              v-model="userInput"
              type="textarea"
              :rows="1"
              placeholder="请输入你的问题..."
              :disabled="loading"
              @keyup.enter.native="sendMessage"
              resize="none">
            </el-input>
            <div class="input-actions">
              <el-button
                type="text"
                size="small"
                @click="showQuickQuestions = !showQuickQuestions"
                title="常用问题">
                <i class="el-icon-question"></i>
              </el-button>
              <el-button
                type="primary"
                size="small"
                :loading="loading"
                @click="sendMessage">
                发送
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { aiChat } from '@/api/ai/chat'

export default {
  name: "AiHub",
  data() {
    return {
      userInput: "",
      loading: false,
      currentSessionId: 647006,
      showQuickQuestions: false,
      chatSessions: [
        {
          id: 647006,
          title: "咨询记录",
          messages: []
        }
      ],
      quickQuestionRoles: [
        {
          name: "生产主管",
          questions: [
            "我是生产主管 我想问生产流程怎么样进行的",
            "如何创建生产工单？",
            "怎么查看生产进度？",
            "如何进行工单派工？"
          ]
        },
        {
          name: "车间操作员",
          questions: [
            "如何接收工单任务？",
            "怎么进行工序报工？",
            "设备故障如何处理？",
            "质量问题如何上报？"
          ]
        },
        {
          name: "质检员",
          questions: [
            "如何创建质检单？",
            "质检流程是什么？",
            "不合格品如何处理？",
            "质检标准在哪里查看？"
          ]
        },
        {
          name: "仓库管理员",
          questions: [
            "如何查询库存信息？",
            "怎么进行物料出库？",
            "如何处理物料入库？",
            "库存盘点怎么操作？"
          ]
        },
        {
          name: "计划员",
          questions: [
            "如何制定生产计划？",
            "MRP运算怎么执行？",
            "物料需求如何计算？",
            "交期如何安排？"
          ]
        }
      ]
    };
  },
  computed: {
    currentMessages() {
      const session = this.chatSessions.find(s => s.id === this.currentSessionId);
      return session ? session.messages : [];
    }
  },
  mounted() {
    // 初始化欢迎消息
    this.appendMessage(`您好！我是灵动制联MES系统的智能助理小钢铁！我可以帮助您解答关于生产管理、工单派工、质检流程、库存管理等MES系统相关问题。

请问您是哪个岗位的？（例如：生产主管、车间操作员、质检员、仓库管理员、计划员等）
以及今天需要咨询哪方面的问题呢？（如生产工艺、工单操作、质检流程、仓库管理、MRP运算等）

请您简单描述一下遇到的问题或需求，我会为您提供专业的指导！

💡 您也可以点击右下角的问号按钮查看常用问题。`, 'ai');
  },
  methods: {
    sendMessage() {
      const query = this.userInput.trim();
      if (query && !this.loading) {
        this.appendMessage(query, 'user');
        this.userInput = '';
        this.loading = true;

        // 显示思考过程提示
        const thinkingMessage = this.getThinkingMessage(query);
        this.appendMessage(thinkingMessage, 'thinking');

        // 调用SpringAI接口
        aiChat({
          prompt: query,
          chatId: this.currentSessionId.toString()
        }).then(response => {
          // 移除思考提示
          this.removeThinkingMessage();

          // 处理响应数据
          let aiResponse;
          if (response.data && response.data.data) {
            aiResponse = response.data.data;
          } else if (response.data) {
            aiResponse = response.data;
          } else {
            aiResponse = response;
          }
          this.appendMessage(aiResponse, 'ai');
        }).catch(error => {
          // 移除思考提示
          this.removeThinkingMessage();

          console.error('Error fetching AI response:', error);
          if (error.message && error.message.includes('timeout')) {
            this.appendMessage('请求超时，请稍后重试。如果是复杂查询，可能需要更长时间处理。', 'ai');
          } else {
            this.appendMessage('抱歉，AI服务暂时不可用，请稍后重试。', 'ai');
          }
        }).finally(() => {
          this.loading = false;
        });
      }
    },
    sendQuickQuestion(question) {
      this.userInput = question;
      this.showQuickQuestions = false;
      this.sendMessage();
    },
    getThinkingMessage(query) {
      const lowerQuery = query.toLowerCase();

      if (lowerQuery.includes('查询') || lowerQuery.includes('显示') || lowerQuery.includes('列表')) {
        if (lowerQuery.includes('工厂') || lowerQuery.includes('厂区')) {
          return '🏭 小钢正在查询工厂信息...';
        } else if (lowerQuery.includes('生产') || lowerQuery.includes('工单')) {
          return '📋 小钢正在查询生产数据...';
        } else if (lowerQuery.includes('质检') || lowerQuery.includes('质量')) {
          return '🔍 小钢正在查询质检数据...';
        } else if (lowerQuery.includes('库存') || lowerQuery.includes('物料')) {
          return '📦 小钢正在查询库存数据...';
        } else if (lowerQuery.includes('设备')) {
          return '⚙️ 小钢正在查询设备数据...';
        } else {
          return '🔍 小钢正在查询相关数据...';
        }
      } else {
        return '🤔 小钢正在思考中，请稍候...';
      }
    },
    removeThinkingMessage() {
      const session = this.chatSessions.find(s => s.id === this.currentSessionId);
      if (session && session.messages.length > 0) {
        const lastMessage = session.messages[session.messages.length - 1];
        if (lastMessage.sender === 'thinking') {
          session.messages.pop();
        }
      }
    },
    appendMessage(text, sender) {
      const session = this.chatSessions.find(s => s.id === this.currentSessionId);
      if (session) {
        session.messages.push({
          text: text,
          sender: sender,
          timestamp: new Date().toLocaleTimeString()
        });
        this.$nextTick(() => {
          const chatMessages = this.$refs.chatMessages;
          if (chatMessages) {
            chatMessages.scrollTop = chatMessages.scrollHeight;
          }
        });
      }
    },
    newChat() {
      const newSessionId = Date.now();
      this.chatSessions.unshift({
        id: newSessionId,
        title: `新对话 ${this.chatSessions.length + 1}`,
        messages: []
      });
      this.currentSessionId = newSessionId;
      this.appendMessage(`您好！我是灵动制联MES系统的智能助理小钢！我可以帮助您解答关于生产管理、工单派工、质检流程、库存管理等MES系统相关问题。

请问您是哪个岗位的？（例如：生产主管、车间操作员、质检员、仓库管理员、计划员等）
以及今天需要咨询哪方面的问题呢？

💡 您也可以点击右下角的问号按钮查看常用问题。`, 'ai');
    },
    switchSession(sessionId) {
      this.currentSessionId = sessionId;
    },
    formatMessage(text) {
      if (!text) return '';

      // 检查是否包含表格格式
      if (text.includes('|') && text.includes('---')) {
        return this.convertMarkdownTableToHtml(text);
      }

      // 普通文本，转换换行符
      return text.replace(/\n/g, '<br>');
    },
    convertMarkdownTableToHtml(text) {
      const lines = text.split('\n');
      let html = '';
      let inTable = false;
      let headerAdded = false;

      for (let i = 0; i < lines.length; i++) {
        const line = lines[i].trim();

        if (line.includes('|') && !line.includes('---')) {
          if (!inTable) {
            html += '<table class="ai-table">';
            inTable = true;
            headerAdded = false;
          }

          const cells = line.split('|').map(cell => cell.trim()).filter(cell => cell);

          // 第一行作为表头
          if (!headerAdded) {
            html += '<thead><tr>';
            cells.forEach(cell => {
              html += `<th>${cell}</th>`;
            });
            html += '</tr></thead><tbody>';
            headerAdded = true;
          } else {
            html += '<tr>';
            cells.forEach(cell => {
              html += `<td>${cell}</td>`;
            });
            html += '</tr>';
          }
        } else if (line.includes('---')) {
          // 跳过分隔行
          continue;
        } else {
          if (inTable) {
            html += '</tbody></table>';
            inTable = false;
            headerAdded = false;
          }
          if (line) {
            html += `<p>${line}</p>`;
          }
        }
      }

      if (inTable) {
        html += '</tbody></table>';
      }

      return html;
    }
  }
};
</script>

<style scoped>
.ai-hub-container {
  height: 100vh;
  background: #f5f7fa;
  display: flex;
  flex-direction: column;
}

/* 顶部导航栏 */
.header {
  background: white;
  padding: 15px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e8eaec;
  box-shadow: 0 2px 8px rgba(0,0,0,0.06);
}

.header h1 {
  color: #4285f4;
  font-size: 20px;
  font-weight: 600;
  margin: 0;
}

/* 主体内容区域 */
.main-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

/* 左侧会话记录 */
.sidebar {
  width: 280px;
  background: white;
  border-right: 1px solid #e8eaec;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 20px;
  border-bottom: 1px solid #e8eaec;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.sidebar-header span {
  font-weight: 500;
  color: #333;
}

.chat-sessions {
  flex: 1;
  overflow-y: auto;
  padding: 10px 0;
}

.session-item {
  padding: 15px 20px;
  cursor: pointer;
  border-bottom: 1px solid #f5f7fa;
  transition: background 0.3s;
  display: flex;
  align-items: center;
  gap: 10px;
}

.session-item:hover {
  background: #f8f9fa;
}

.session-item.active {
  background: #e3f2fd;
  border-right: 3px solid #4285f4;
}

.session-item i {
  color: #666;
  font-size: 16px;
}

.session-title {
  flex: 1;
  font-weight: 500;
  color: #333;
}

.session-id {
  font-size: 12px;
  color: #999;
  background: #f0f0f0;
  padding: 2px 8px;
  border-radius: 10px;
}

/* 右侧聊天区域 */
.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
}

.chat-header {
  padding: 24px;
  border-bottom: 1px solid #e8eaec;
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
}

.chat-title {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 8px;
}

.ai-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background: linear-gradient(135deg, #4285f4 0%, #5a9cf8 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
  box-shadow: 0 4px 12px rgba(66, 133, 244, 0.3);
}

.title-content {
  flex: 1;
}

.ai-name {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  display: block;
  margin-bottom: 4px;
}

.ai-status {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #666;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #52c41a;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(82, 196, 26, 0.7);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(82, 196, 26, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(82, 196, 26, 0);
  }
}

.chat-subtitle {
  color: #666;
  font-size: 14px;
  font-weight: 500;
  padding-left: 64px;
}

/* 聊天消息区域 */
.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: #fafbfc;
}

.message-wrapper {
  display: flex;
  margin-bottom: 20px;
  gap: 12px;
}

.message-wrapper.user {
  flex-direction: row-reverse;
}

.message-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: #4285f4;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 16px;
  flex-shrink: 0;
}

.message-wrapper.user .message-avatar {
  background: #34a853;
}

.message-content {
  max-width: 70%;
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.message-wrapper.user .message-content {
  align-items: flex-end;
}

.message-text {
  background: white;
  padding: 16px 20px;
  border-radius: 16px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
  line-height: 1.6;
  word-wrap: break-word;
  border: 1px solid #f0f0f0;
  position: relative;
}

.message-text::before {
  content: '';
  position: absolute;
  top: 15px;
  left: -8px;
  width: 0;
  height: 0;
  border-top: 8px solid transparent;
  border-bottom: 8px solid transparent;
  border-right: 8px solid white;
}

.message-wrapper.user .message-text {
  background: linear-gradient(135deg, #4285f4 0%, #5a9cf8 100%);
  color: white;
  border-color: #4285f4;
}

.message-wrapper.user .message-text::before {
  left: auto;
  right: -8px;
  border-left: 8px solid #4285f4;
  border-right: none;
}

/* AI消息特殊样式 */
.message-wrapper.ai .message-text {
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  border-left: 4px solid #4285f4;
  box-shadow: 0 3px 12px rgba(66, 133, 244, 0.1);
}

/* 思考中消息样式 */
.message-wrapper.thinking .message-text {
  background: linear-gradient(135deg, #fff3cd 0%, #ffeaa7 100%);
  border-left: 4px solid #f39c12;
  color: #856404;
  font-style: italic;
  box-shadow: 0 2px 8px rgba(243, 156, 18, 0.1);
}

.thinking-text {
  position: relative;
  overflow: hidden;
}

.thinking-text::after {
  content: '...';
  animation: thinking-dots 1.5s infinite;
  font-weight: bold;
}

@keyframes thinking-dots {
  0%, 20% {
    opacity: 0;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}

.thinking-icon {
  animation: spin 1s linear infinite;
  color: #f39c12;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.message-time {
  font-size: 12px;
  color: #999;
  padding: 0 5px;
}

/* 快捷问题区域 */
.quick-questions {
  border-top: 1px solid #e8eaec;
  background: #f8f9fa;
  max-height: 300px;
  overflow-y: auto;
}

.quick-questions-header {
  padding: 15px 20px 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 500;
  color: #333;
  border-bottom: 1px solid #e0e0e0;
}

.quick-questions-content {
  padding: 15px 20px;
}

.role-questions {
  margin-bottom: 20px;
}

.role-questions:last-child {
  margin-bottom: 0;
}

.role-title {
  font-size: 14px;
  font-weight: 500;
  color: #4285f4;
  margin-bottom: 10px;
  padding-left: 8px;
  border-left: 3px solid #4285f4;
}

.questions-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.question-btn {
  background: white;
  border: 1px solid #e0e0e0;
  color: #666;
  border-radius: 16px;
  padding: 6px 12px;
  font-size: 12px;
  transition: all 0.3s;
  max-width: 200px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.question-btn:hover {
  background: #4285f4;
  color: white;
  border-color: #4285f4;
  transform: translateY(-1px);
}

/* 输入区域 */
.chat-input {
  padding: 20px;
  border-top: 1px solid #e8eaec;
  background: white;
}

.input-wrapper {
  display: flex;
  align-items: flex-end;
  gap: 12px;
  background: #f8f9fa;
  border: 1px solid #e0e0e0;
  border-radius: 12px;
  padding: 12px;
  transition: border-color 0.3s;
}

.input-wrapper:focus-within {
  border-color: #4285f4;
  box-shadow: 0 0 0 2px rgba(66, 133, 244, 0.1);
}

.input-wrapper .el-textarea {
  flex: 1;
}

.input-wrapper .el-textarea >>> .el-textarea__inner {
  border: none;
  background: transparent;
  resize: none;
  padding: 0;
  font-size: 14px;
  line-height: 1.5;
}

.input-wrapper .el-textarea >>> .el-textarea__inner:focus {
  box-shadow: none;
}

.input-actions {
  display: flex;
  align-items: center;
}

.input-actions .el-button {
  border-radius: 8px;
  padding: 8px 16px;
}

/* 滚动条样式 */
.chat-messages::-webkit-scrollbar,
.chat-sessions::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track,
.chat-sessions::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb,
.chat-sessions::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb:hover,
.chat-sessions::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* AI表格样式 */
.ai-table {
  width: 100%;
  border-collapse: collapse;
  margin: 15px 0;
  font-size: 13px;
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0,0,0,0.08);
  border: 1px solid #e8eaec;
}

.ai-table th,
.ai-table td {
  padding: 12px 16px;
  text-align: left;
  border-bottom: 1px solid #f0f0f0;
  word-wrap: break-word;
  max-width: 150px;
  vertical-align: middle;
}

.ai-table th {
  background: linear-gradient(135deg, #4285f4 0%, #5a9cf8 100%);
  font-weight: 600;
  color: white;
  border-bottom: none;
  font-size: 14px;
  text-shadow: 0 1px 2px rgba(0,0,0,0.1);
}

.ai-table tbody tr {
  transition: all 0.3s ease;
}

.ai-table tbody tr:hover {
  background: #f8f9ff;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(66, 133, 244, 0.1);
}

.ai-table tr:last-child td {
  border-bottom: none;
}

.ai-table tbody tr:nth-child(even) {
  background: #fafbfc;
}

.ai-table tbody tr:nth-child(even):hover {
  background: #f8f9ff;
}

/* 消息文本样式 */
.message-text p {
  margin: 5px 0;
  line-height: 1.6;
}

.message-text br {
  line-height: 1.6;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .sidebar {
    width: 240px;
  }

  .message-content {
    max-width: 85%;
  }

  .ai-table {
    font-size: 11px;
  }

  .ai-table th,
  .ai-table td {
    padding: 6px 8px;
    max-width: 80px;
  }
}
</style>